#include "ImageTexture.h"
#include "../Basis/Image.h"

ImageTexture::ImageTexture(char* file_name)
{
	image = new Image();
	image->readPPM(file_name);
}

//	bilinear interpolation
rgb ImageTexture::value(const Vector2& uv, const Vector3& p) const
{
	float u = uv.x() - (int)(uv.x());
	float v = uv.y() - (int)(uv.y());
	//	u, v are in [0, 1)

	u *= (image->getWidth() - 1);
	v *= (image->getHeight() - 1);
	//	now u, v are in [0, n - 1)

	int iu = (int)u;
	int iv = (int)v;
	//	iu, iv are from 0, 1, 2, ..., n - 2;
	float tu = u - iu;
	float tv = v - iv;

	rgb c = image->getPixel(iu, iv) * (1 - tu) * (1 - tv)
		+ image->getPixel(iu + 1, iv) * tu * (1 - tv)
		+ image->getPixel(iu, iv + 1) * (1 - tu) * tv
		+ image->getPixel(iu + 1, iv + 1) * tu * tv;

	return c;
}